package com.study.talk.ui.adapter.chat

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.study.talk.data.model.GroupMessageRecord
import com.study.common.ToastUtil
import com.study.talk.R
import com.study.talk.ui.adapter.base.BaseListAdapter
import com.study.talk.databinding.GroupMsgItemBinding
import com.study.talk.ui.app.chat.GroupChatViewModel
import com.study.talk.ui.app.self.SelfActivity
import com.study.talk.utils.TimeAgoUtils
import com.study.talk.utils.extras.start
import com.study.talk.utils.extras.toImage
import com.study.talk.utils.extras.toUserDetails

class GroupsMsgAdapter(private val groupChatViewModel: GroupChatViewModel) : BaseListAdapter<GroupMessageRecord, GroupsMsgAdapter.ViewHolder>() {

    class ViewHolder(val context: Context, val binding: GroupMsgItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    private val selectMap = mutableMapOf<Int, Boolean>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            parent.context, DataBindingUtil.inflate(
                LayoutInflater.from(parent.context), R.layout.group_msg_item, parent, false
            )
        )
    }

    private fun imageOnClickListener(position: Int, context: Context) {
        val imageList = mutableListOf<String>()
        currentList.filter { it.messageType == 1 }.mapTo(imageList) { it.content }
        context.apply {
            toImage(imageList,position)
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int, payloads: MutableList<Any>) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
        } else {
            for (payload in payloads) {
                when (payload as String) {
                    "select" -> selectMode(holder, position, true)
                    "normal" -> selectMode(holder, position, false)
                }
            }
        }
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val msg = getItem(position)
        holder.binding.msg = msg
        if (msg.messageType == 3) {
            holder.binding.groupMsgNotice.groupNoticeLayout.visibility = View.VISIBLE
        } else {
            //选中 or 取消选中消息
            holder.binding.chatMsgSelect.setOnCheckedChangeListener { _, isChecked ->
                selectMap[msg.id] = isChecked
            }
            if (msg.self) {
                holder.binding.groupMsgRight.groupMsgRightLayout.visibility = View.VISIBLE
                holder.binding.groupMsgRight.msgContentTime.text = TimeAgoUtils.format(msg.dateTime)
                holder.binding.groupMsgRight.msgContentHeadImg.setOnClickListener {
                    holder.context.apply {
                        toUserDetails(msg.userId)
                    }
                }
                holder.binding.groupMsgRight.msgContentTextView.setOnLongClickListener {
                    showMenu(position,it)
                    return@setOnLongClickListener true
                }
                holder.binding.groupMsgRight.msgContentImageView.setOnClickListener {
                    imageOnClickListener(position, holder.context)
                }
            } else {
                holder.binding.groupMsgLeft.groupMsgLeftLayout.visibility = View.VISIBLE
                holder.binding.groupMsgLeft.msgContentTime.text = TimeAgoUtils.format(msg.dateTime)
                holder.binding.groupMsgLeft.msgContentHeadImg.setOnClickListener {
                    holder.context.apply {
                        start(SelfActivity::class.java)
                    }
                }
                holder.binding.groupMsgLeft.msgContentTextView.setOnLongClickListener {
                    showMenu(position,it)
                    return@setOnLongClickListener true
                }
                holder.binding.groupMsgLeft.msgContentImageView.setOnClickListener {
                    imageOnClickListener(position, holder.context)
                }
            }
        }
    }

    private fun selectMode(holder: ViewHolder, position: Int, mode: Boolean) {
        if (getItem(position).messageType != 3){ //通知不需要
            holder.binding.chatMsgSelect.isChecked = selectMap.getOrDefault(getItem(position).id, false)
            holder.binding.chatMsgSelect.visibility = if (mode) View.VISIBLE else View.GONE
        }
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }

    /** 长按消息体弹窗 */
    private fun showMenu(position: Int, view: View) {
        val contentView = createContentView(view)
        val window = createPopupView(contentView, view)
        val entry = IntArray(2)
        view.getLocationOnScreen(entry)
        window.showAtLocation(
            view,
            Gravity.NO_GRAVITY,
            entry[0] + view.width / 2 - contentView.width / 2,
            entry[1] - contentView.height - 20
        )
        initPopupWindowAction(contentView, window, position)
    }

    /** 初始化popupWindow的ContentView */
    private fun createContentView(view: View): View {
        return LayoutInflater.from(view.context).inflate(R.layout.msg_pop_option, null).apply {
            measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            )
            layout(0, 0, measuredWidth, measuredHeight)
        }
    }

    /** 创建PopupWindow */
    private fun createPopupView(contentView: View, contextView: View): PopupWindow {
        val window = PopupWindow(
            contextView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )
        window.isOutsideTouchable = true
        window.isFocusable = true
        window.isTouchable = true
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window.contentView = contentView
        return window
    }

    /** 初始化popupWindow中ContentView内部子View的点击事件 */
    private fun initPopupWindowAction(
        popView: View, popupWindow: PopupWindow, position: Int
    ) {
        popView.findViewById<LinearLayoutCompat>(R.id.msg_option_multiply_select)
            .setOnClickListener {
                selectMap[getItem(position).id] = true
                groupChatViewModel.changeSelectModel(true)
                popupWindow.dismiss()
            }

        popView.findViewById<LinearLayoutCompat>(R.id.msg_option_smart_analyze).setOnClickListener {
            groupChatViewModel.notifyAnalyzeContent(getItem(position).content)
            popupWindow.dismiss()
        }

        popView.findViewById<LinearLayoutCompat>(R.id.msg_option_other).setOnClickListener {
            ToastUtil.showToast(it.context, "功能开发中")
            popupWindow.dismiss()
        }
    }

    fun selectModel() {
        for (i in 0 until itemCount) {
            notifyItemChanged(i, "select")
        }
    }

    /** 普通模式 */
    fun normalModel() {
        for (i in 0 until itemCount) {
            notifyItemChanged(i, "normal")
        }
        clearSelected()
    }

    /** 多选模式 */
    fun getSelectMsg(): List<GroupMessageRecord> {
        return currentList.filter {
            selectMap.getOrDefault(it.id, false)
        }
    }

    /** 清除所有的选择 */
    fun clearSelected() {
        selectMap.clear()
    }

}
